//
//  NotificationService.swift
//  NotiService
//
//  Created by Wei Zhou on 2017/8/17.
//  Copyright © 2017年 Wulian. All rights reserved.
//

import UserNotifications
import AVFoundation
import CoreBluetooth




class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    
    //var curPeripheral : CBPeripheral? = UserDefaults.standard.object(forKey: "curPeripheral") as? CBPeripheral

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            // Modify the notification content here...
            bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
            
            try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [AVAudioSessionCategoryOptions.mixWithOthers])
            let speechSyn = AVSpeechSynthesizer()
            let speechUtt = AVSpeechUtterance(string: bestAttemptContent.body)
            speechUtt.rate = 0.35
            speechSyn.speak(speechUtt)
            
            contentHandler(bestAttemptContent)
        }
    }
    
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
            contentHandler(bestAttemptContent)
        }
    }

}
